var PRICE_CONVERT = 1000000,
    MARKLINE_COLOR = '#fff';

/* faseClick */
$(function () {
    FastClick.attach(document.body);
});

/* window。resize */
window.onresize = function () {
    if (window.$containerObj) {
        $containerObj.chartObj.chart.resize();
    }
};

/* 同步请求一个接口，维修请求接口慢解决方案 */
function dealMaintainSlow() {
    publicAjax(basePath + 'charts/area/maintain/init','post', null, function(data){
        console.log(data.msg);
    }, true, {async: false});
}

/*公共的ajax请求。
url:不带basePath全路径，
项目上下文是basePath，
 type:请求方式,通常是post请求,
 parameter:参数 ，json类型
 fn回调，将返回结果交给调用方处理
 */
function publicAjax(url, type, parameter, fn, closeLoading, param) {
    if (typeof fn !== 'function') {
        flavrShowByTime("回调必须是个函数,function", null, "danger", false);
        return;
    }
    closeLoading ? null : loading();
    /* 是否反响代理 */
    $.ajax($.extend({
        url: url,
        type: type,
        data: parameter || {},
        success: function (data) {
            if (data.ret === 1) {
                fn(data);
            } else if (data.ret === 0) {
                flavrShowByTime(data.msg, null, 'error', false);
            } else if (data.ret === 500) {
                flavrShowByTime(data.msg, null, 'error', false);
            } else if (data.ret === 404) {
                flavrShowByTime(data.msg, null, 'error', false);
            } else {
                location.href = basePath + '/logout';
            }
            closeLoading ? null : loading(true);
        },
        error: function (data) {
            console.log("出错la。。。。");
            console.log(data);
            loading(true);
        }
    }, param));
}

/*
* Loading动画
* */
function loading(isOver, time) {
    var loadingDiv = $('#loading-div');
    if (isOver === true) {
        loadingDiv.hide();
    } else {
        if (loadingDiv.length) {
            loadingDiv.show();
        } else {
            $('body').append('<div id="loading-div" style="display: none;"><img src="' + basePath + '/public/images/loading.gif" alt="正在加载，请稍候……"></div>').append('<style>#loading-div {position: fixed;width: 100%;height: 100%;left: 0;top: 0;background: rgba(0,0,0,0.5);z-index: 99999;}#loading-div img {display: block;width: 4rem;height: 4rem;position: absolute;left: 50%;top: 50%;margin: -2rem 0 0 -2rem;}</style>');
            $('#loading-div').show();
        }
    }
    if (typeof isOver === 'function') setTimeout(isOver, time || 5);
}

/* 获取basePath */
function getBasePath() {
    //获取当前网址，如： http://localhost:8080/ems/Pages/Basic/Person.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： /ems/Pages/Basic/Person.jsp
    var pathName = window.document.location.pathname;
    var pos = pathName === "/" ? (curWwwPath.length - 1) : curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8080
    var localhostPath = curWwwPath.substring(0, pos);
    //获取带"/"的项目名，如：/ems
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
    //获取项目的basePath   http://localhost:8080/ems/
    window.basePath = localhostPath + projectName + "/";
    return basePath;
}

getBasePath();

/* 提示信息框 */
function flavrShowByTime(msg, urls, color, isHref) {
    new $.flavr({
        content: msg,
        autoclose: true,
        closeOverlay: true,
        closeEsc: true,
        buttons: [{text: 'ok', style: color}],
        timeout: 3000,
        onClose: function () {
            if (isHref && urls != null) {
                window.location.href = urls;
            }
        }
    });
}

function flavrShow(msg, urls, color, isHref, fn) {
    new $.flavr({
        content: msg,
        autoclose: false,
        closeOverlay: true,
        closeEsc: true,
        buttons: [{text: '确认', style: 'info', action: fn}, {text: '取消', style: 'primary'}],
        onClose: function () {
            if (isHref && urls != null) {
                window.location.href = urls;
            }
        }
    });
}

/*
* 根据参数名获取url中的参数
* name  参数名
* */
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

// 保存两位小数
function fix2(string) {
    return (parseFloat(string || 0) || 0).toFixed(2);
}

// 保存为整数或者 0
function fix0(string) {
    return parseInt(string || 0) || 0;
}

function fixStr(string) {
    return string || '';
}

function fixLine(string) {
    if (string == 0) return 0;
    return string || '-';
}

function fixNull(string) {
    if (string && string == 'null') {
        return null;
    } else {
        return string;
    }
}

function fixFD0(string) {
    return string == '0' ? 0 : (string || '');
}

//最小值
Array.prototype.min = function (key) {
    var min;
    if (key) {
        min = parseFloat(this[0][key] || 0);
        for (var i = 1; i < this.length; i++) {
            if (parseFloat(this[i][key] || 0) < min) {
                min = parseFloat(this[i][key] || 0);
            }
        }
    } else {
        min = parseFloat(this[0] || 0);
        for (var i = 1; i < this.length; i++) {
            if (parseFloat(this[i] || 0) < min) {
                min = parseFloat(this[i] || 0);
            }
        }
    }
    return min;
};
//最大值
Array.prototype.max = function (key) {
    var max;
    if (key) {
        max = parseFloat(this[0][key] || 0);
        for (var i = 1; i < this.length; i++) {
            if (parseFloat(this[i][key] || 0) > max) {
                max = parseFloat(this[i][key] || 0);
            }
        }
    } else {
        max = parseFloat(this[0] || 0);
        for (var i = 1; i < this.length; i++) {
            if (parseFloat(this[i] || 0) > max) {
                max = parseFloat(this[i] || 0);
            }
        }
    }
    return max;
};
Array.prototype.hasValue = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            return true;
        }
    }
    return false;
};
Array.prototype.removeByValue = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            this.splice(i, 1);
            break;
        }
    }
};
/*
* 计算JSON数字的总数
* */
Array.prototype.calTotal = function () {
    var keyArr = [];
    var total = {};
    for (var i = 0; i < this.length; i++) {
        for (var key in this[i]) {
            if (!keyArr.hasValue(key)) keyArr.push(key);
        }
        for (var k = 0; k < keyArr.length; k++) {
            if (typeof this[i][keyArr[k]] === 'object' && this[i][keyArr[k]] !== null) {
                total[keyArr[k]] = (total[keyArr[k]] || []).concat(this[i][keyArr[k]]);
            } else {
                total[keyArr[k]] = (parseFloat(total[keyArr[k]]) || 0) + (parseFloat(this[i][keyArr[k]]) || 0);
            }
        }
    }
    this[-1] = total;
    return this;
};
/*
* 根据数组的子JSON的key排序
* 默认倒序排序[{pis:dds},{}]
* 不传key就返回原数组
* */
Array.prototype.sortByKey = function (sorting, key, deep) {
    if (arguments.length > 0 && arguments.length < 4) {
        if (arguments.length === 1) {
            if (typeof sorting === 'string') {
                deep = true;
                key = sorting;
                sorting = 'desc';
            } else {
                console.log('请传入按照什么key排序');
                return;
            }
        } else if (arguments.length === 2) {
            if (typeof sorting === 'string' && (typeof key === 'string')) {
                sorting = (sorting === 'desc' || sorting === 'asc') ? sorting : 'desc';
                deep = true;
            } else if (typeof sorting === 'string' && (typeof key === 'boolean')) {
                deep = key;
                key = sorting;
                sorting = 'desc';
            } else {
                console.log('请传入按照什么key排序');
                return;
            }
        }
    } else {
        console.log('请传入1-3个参数[排序方式(desc|asc),按照什么字段排序,是否排序子数组(默认true)]');
        return;
    }
    if (key === '') return this;
    var reg = /^(-?\d+)(\.\d+)?$/,
        isNum = true;
    for (var i = 0; i < this.length; i++) {
        if (this[i][key] && !reg.test(this[i][key])) {
            isNum = false;
            break;
        }
    }
    this.sort(function (a, b) {
        return (sorting === 'asc' ? 1 : -1) * (isNum
            ? a[key] - b[key]
            : (a[key] || '').localeCompare(b[key], 'zh-Hans-CN', {sensitivity: 'accent'}))
    });
    if (deep) {
        for (var i = 0; i < this.length; i++) {
            if (this[i].list && (typeof this[i].list === 'object')) this[i].list.sortByKey(sorting, key, deep);
        }
    }
    if (this[-1] && this[-1].list && (typeof this[-1].list === 'object')) this[-1].list.sortByKey(sorting, key, deep);
    return this;
};
/*
* 根据指定key，value获取Index
* */
Array.prototype.getIndexByKey = function (key, value) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][key] == value) return i;
    }
    return -1;
};
/*
* 根据name获取Id
* */
Array.prototype.getIdByName = function (name) {
    for (var i = 0; i < this.length; i++) {
        if (this[i].name === name) return this[i].id;
    }
    return -1;
};

function convert(sValue, sDataType) {
    if (sDataType) {
        switch (sDataType) {
            case "int":
                return parseInt(sValue);
            case "float":
                return parseFloat(sValue);
            case "date":
                return new Date(Date.parse(sValue));
            default:
                return sValue;
        }
    } else {
        return /^[0-9]+(.[0-9]{2})?$/.test(sValue) ? parseFloat(sValue) : sValue;
    }
}

//判断:当前元素是否是被筛选元素的子元素
jQuery.fn.isChildOf = function (b) {
    return (this.parents(b).length > 0);
};
//判断:当前元素是否是被筛选元素的子元素或者本身
jQuery.fn.isChildAndSelfOf = function (b) {
    return (this.closest(b).length > 0);
};

/*
* 字符串转JSON
* {year:2015,type:154}
* */
function string2json(str) {
    var json = {};
    var strArr = str.slice(1, -1).split(',');
    for (var i = 0; i < strArr.length; i++) {
        json[strArr[i].split(':')[0]] = strArr[i].split(':')[1]
    }
    return json;
}

//导出Excel
function exportExcel(modal) {
    // 3秒之内无法点击
    loading();
    var _this = $(modal).find('.export_excel');
    _this.off().find('i').removeClass('fa-upload').addClass('fa-hourglass').css('cursor', 'wait');
    setTimeout(function () {
        _this.find('i').removeClass('fa-hourglass').addClass('fa-upload').css('cursor', 'pointer');
        _this.click(exportExcel);
        loading(true);
    }, 3000);
    var table = $(modal).find('table:visible');
    var thead = table.find('thead');
    var tbody = table.find('tbody');
    var tfoot = table.find('tfoot');
    var tr = null;
    /* 获取thead */
    var theadArr = [];
    tr = thead.find('th');
    for (var i = 0; i < tr.length; i++) {
        theadArr.push(tr.eq(i).text());
    }
    /* 获取tbody */
    var tbodyArr = {};
    tr = tbody.find('tr');
    var td = tbody.find('tr td[rowspan]');
    if (td.length) {
        for (var i = 0; i < td.length; i++) {
            var key = td.eq(i).text();
            var index = td.eq(i).parent().index();
            var count = td.eq(i).attr('rowspan');
            var arr = [];
            for (var j = index; j < index + parseInt(count); j++) {
                var arr1 = [];
                var tdEl = tr.eq(j).find('td');
                var start = j === index ? 1 : 0;
                for (var k = start; k < tdEl.length; k++) {
                    arr1.push(tdEl.eq(k).text());
                }
                arr.push(arr1)
            }
            tbodyArr[key] = arr;
        }
    } else {
        var trArr = [];
        for (var i = 0; i < tr.length; i++) {
            var trArrTemp = [];
            for (var j = 0; j < tr.eq(i).children().length; j++) {
                trArrTemp.push(tr.eq(i).children().eq(j).text());
            }
            trArr.push(trArrTemp);
        }
        tbodyArr = {0: trArr};
    }
    /* tfoot */
    var tfootArr = [];
    tr = tfoot.find('td');
    for (var i = 0; i < tr.length; i++) {
        tfootArr.push(tr.eq(i).text());
    }

    var form = $('#exportExcel');
    if (!form.length) {
        $('body').append('<form action="' + basePath + '/charts/excelexport" method="post" id="exportExcel" style="display:none;">' +
            '            <input type="text" name="fileName" class="fileName">' +
            '            <input type="text" name="thead" class="thead">' +
            '            <input type="text" name="tbody" class="tbody">' +
            '            <input type="text" name="tfoot" class="tfoot">' +
            '        </form>');
        form = $('#exportExcel');
    }
    form.find('.fileName').val($(modal).find('.iziModal-header-title').text() || $(modal).find('.model-title').text());
    form.find('.thead').val(JSON.stringify(theadArr));
    form.find('.tbody').val(JSON.stringify(tbodyArr));
    form.find('.tfoot').val(JSON.stringify(tfootArr));
    form.submit();
}

function min2bigger(value) {
    var json = {};
    value = value || 0;
    if (value / 60 / 24 >= 1) {
        json = {value: fix2(value / 60 / 24), unit: '天'};
    } else if (value / 60 >= 1) {
        json = {value: fix2(value / 60), unit: '小时'};
    } else {
        json = {value: value, unit: '分钟'};
    }
    json.all = json.value + json.unit;
    return json;
}

/* 设置jQuery title */
$.fn.extend({
    /* 设置获取title */
    title: function (value) {
        return value ? this.attr('title', value) : this.attr('title');
    },
    /* 设置内容并且设置title */
    textAndTitle: function (value) {
        return this.text(value).attr('title', value);
    }
});
